import my_importer
my_importer.myImport("Gitee")
my_importer.myImport("MyPush")
import time
import datetime
import calendar
import random
import requests
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = "TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-256-GCM-SHA384:ECDHE:!COMPLEMENTOFDEFAULT"
requests.packages.urllib3.disable_warnings()
import json
import copy
import os
import base64
import re
import sys
import pickle
import hashlib
import traceback

import MyPush
from Gitee import Gitee
#判断是否为腾讯云函数环境
yun = os.environ.get('TENCENTCLOUD_RUNENV')
path = ""
if yun == "SCF":
    path = "/tmp/" + path           
num = 0
log = {}
log["log"] = ""
gitee = None
myPush = None
#全局变量
def getGitee():
    global gitee
    if gitee == None:
        url = "https://gitee.com/fpanlong/lianTong/raw/master/gitee.json"
        key = my_importer.password   
        gitee = Gitee.getGitee(url,key)
    return gitee
gitee = getGitee()

def getFile(fileName,commit = 0):
    data = gitee.getFile(fileName,commit)
    if data == False:
        print("读取:" + fileName + "失败！")
        data = None
    else:
        print("读取:" + fileName + "成功！")  
        data = json.loads(data)
    return  data        
def update(fileName,data):
    if isinstance(data,(dict,list)):
        data = json.dumps(data,indent=4,ensure_ascii=False)
    if gitee.update(fileName,data) == True:
        print("更新:" + fileName + "成功！")  
        return True
    else:
        print("更新:" + fileName + "失败！")         
        return False 
           
def delete(fileName):
    if gitee.delete(fileName) == True:
        print("删除:" + fileName + "成功！")
        return True  
    else:
        print("删除:" + fileName + "失败！") 
        return False 
        
def deleteFolder(fileName):
    if gitee.deleteFolder(fileName) == True:
        print("删除:" + fileName + "成功！")
        return True  
    else:
        print("删除:" + fileName + "失败！") 
        return False 
    

def CSF(text,data=None):
    csfUrl="https://service-9fihgawf-1304590991.sh.apigw.tencentcs.com/release/" + text +"/"
    if isinstance(data,bytes) :
        data = base64.b64encode(data).decode('utf-8')       
    dict_a = {
    	    "data" : data
    	}
    data = requests.post(url=csfUrl,json=dict_a).json()    
    if data["state"] == True:
        return data["data"]
    else:
        print(data["data"])
        return None
def read(pathName):
    with open(pathName,mode="r") as f:
        return f.read()
             
def write(pathName,data):
    pathDir = pathName[0:pathName.rfind("/")]
    if os.path.exists(pathDir) == False:
        os.makedirs(pathDir)
    if isinstance(data,(dict,list)):
        data = json.dumps(data,indent=4,ensure_ascii=False)    
    with open(pathName,mode="w+") as f:
        f.write(data)
    
def jm_md5(password):
    m = hashlib.md5()  # 构建MD5对象
    m.update(password.encode(encoding='utf-8')) 
    password_md5 = m.hexdigest()
    return password_md5

def updateCode(path):
    list_a = []
    md5Json = {}
    filename = "md5.json"
    updateState = False
    if os.path.exists(filename):
        md5Json = json.loads(read(filename))  
    if os.path.exists(path):
        traverse(path,list_a)
        for index in range(len(list_a)):
            myPath = "code/" + list_a[index].replace(path,"")
            if os.path.isfile(list_a[index]):
                text = read(list_a[index])
                md5 = jm_md5(text)
                if md5Json.get(myPath) !=md5:
                    update(myPath,text)
                    md5Json[myPath] = md5
                    updateState = True
                else:
                    print("文件未修改:" + myPath)
    if updateState == True:
        write(filename,md5Json)
    
#遍历文件文件夹
def traverse(root_path,list_a):
    if os.path.isfile(root_path):
        list_a.append(root_path)
        return True             
    dir_or_files = os.listdir(root_path)
    for dir_file in dir_or_files:
        #获取目录或者文件的路径
        dir_file_path = os.path.join(root_path,dir_file)
        #判断该路径为文件还是路径
        if os.path.isdir(dir_file_path):
            #递归获取所有文件和目录的路径
            traverse(dir_file_path,list_a)
        else:
            list_a.append(dir_file_path)
                        
def push(msg) :
    global myPush
    if myPush == None:
        fileName = "myPush/myPush.json"
        myPush = MyPush.MyPush(getFile(fileName))    
    myPush.push(msg)

def getTime(myTime = ""):
    if myTime == "":
        myTime = time.time()
    if isinstance(myTime,str):
        timeArray = time.strptime(myTime, "%Y年%m月%d日 %H时%M分%S秒")
        timeStamp = float(time.mktime(timeArray))
        return timeStamp
    else:
        return time.strftime("%Y年%m月%d日 %H时%M分%S秒", time.localtime(myTime))

def myPrint(data):
    global log
    if isinstance(data,dict) or isinstance(data,list):
        text = json.dumps(data, indent=4, ensure_ascii=False)
        print(text)
        log["log"] += "\n" + text
    else:
        print(str(data))
        log["log"] += "\n" + str(data)

#字典访问处理数据
def traversalDict_func(dict_a,temp_key,keyList,valueList):
    temp_value = dict_a[temp_key]
    if isinstance(temp_value,list):
        if temp_key in keyList:
            valueList.extend(temp_value)                             
    else:
        if temp_key in keyList:
            valueList.append(temp_value)                     
#遍历字典
def traversalDict(dict_a,keyList,valueList,func):
    #使用isinstance检测数据类型 
    if isinstance(dict_a,dict) :
        for x in range(len(dict_a)):           
            temp_key = list(dict_a.keys())[x]
            temp_value = dict_a[temp_key]
            func(dict_a,temp_key,keyList,valueList)
            traversalDict(dict_a[temp_key],keyList,valueList,func)
    elif isinstance(dict_a,list) :
        for x in range(len(dict_a)):
            traversalDict(dict_a[x],keyList,valueList,func)    

def findDict(dict_a,key):      
    valueList = []
    traversalDict(dict_a,[key],valueList,traversalDict_func)   
    if valueList == []:
        valueList = [""]
    return valueList                
def myRequests(session,url,key=None):
    myPrint(url["title"])
    myData = {} 
    try:
        if url.get("type") == "post":
            html = session.post(url=url["url"],json=url["data"],timeout=20)
        elif url.get("type") == "get":
            html = session.get(url=url["url"],params=url["params"],timeout=20)        
        html.encoding = "utf-8"
        try:
            myData = json.loads(html.text)          
            if key != None and key != "html":
                valueList = []
                traversalDict(myData,[key],valueList,traversalDict_func)   
                if len(valueList) == 1:
                    myData = valueList[0]
                elif  len(valueList) > 1 :
                    myData = valueList
                else:
                    myPrint(myData)
                    myData = "没有找到。"                   
            elif key == "html":
                myData = html                              
        except Exception as e:
            myData = html
        if html.status_code != 200:
            raise Exception(f"状态码:{html.status_code}")                            
    except Exception as e:
        myPrint(str(e) + url["title"] + "失效")
        if key != "":
            time.sleep(1)
            myData = myRequests(session,url,"")
    return myData                           